package com.bbz.crawler.ip.proxy.pool.core.validation;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bbz.crawler.ip.proxy.pool.core.model.CrawlerProxyIp;
import com.bbz.crawler.ip.proxy.pool.core.validation.thread.ValidationThread;
import com.bbz.crawler.ip.proxy.pool.service.ICrawlerProxyIpService;
import com.xxl.job.core.log.XxlJobLogger;

import cn.hutool.core.thread.ThreadUtil;

@Component
public class ProxyIpValidation {

	@Autowired
	ICrawlerProxyIpService crawlerProxyIpService;

	private List<Integer> ids = new ArrayList<>();

	public void run(int threadNum) {
		List<CrawlerProxyIp> list = crawlerProxyIpService.selectList(null);
		int length = list.size();
		int tl = length % threadNum == 0 ? length / threadNum : (length / threadNum + 1);
		Future future = null;
		List<Future> futures = new ArrayList<>();
		ExecutorService pool = Executors.newFixedThreadPool(threadNum);
		for (int i = 0; i < threadNum; i++) {
			int end = (i + 1) * tl;
			future = ThreadUtil
					.execAsync(new ValidationThread("线程[" + (i + 1) + "] ", list, i * tl, end > length ? length : end));
			futures.add(future);
		}
		// 判断是否所有线程已经执行完毕
		try {
			boolean isFinish = pool.awaitTermination(5, TimeUnit.MINUTES);
			System.out.println(isFinish + "==========================");
			// 如果没有执行完
			if (!isFinish) {
				// 线程池执行结束 不在等待线程执行完毕，直接执行下面的代码
				pool.shutdownNow();
			}
			if (futures != null && futures.size() > 0) {
				for (int i = 0; i < futures.size(); i++) {
					try {
						ids.addAll((List<Integer>) futures.get(i).get());
					} catch (ExecutionException e) {
						e.printStackTrace();
					}
				}
				if (ids.size() > 0) {
					crawlerProxyIpService.deleteBatchIds(ids);
				}
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 只给线程池中的线程1小时，然后就继续执行
		XxlJobLogger.log("ProxyIpValidation-JOB Thread it is ok !!!");

	}

}
